package com.ychs.lawyerback01.util;

import com.ychs.lawyerback01.pojo.SealRecord;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class ExcelUtils {

    private static final String[] TITLES = {"序号", "使用日期", "使用原因", "份数", "公章种类", "经办人", "备注"};
    private static final String DATE_PATTERN = "yyyy-MM-dd";

    // 公章类型映射
    private static String getSealTypeName(String type) {
        if (type == null) {
            return "";
        }
        switch (type) {
            case "official":
                return "公章";
            case "contract":
                return "合同专用章";
            case "financial":
                return "财务专用章";
            case "invoice":
                return "发票专用章";
            case "legal":
                return "法定代表人章";
            default:
                return type;
        }
    }

    private static <T> T getSafeValue(T value, T defaultValue) {
        return value != null ? value : defaultValue;
    }

    /**
     * 导出印章使用记录到Excel
     */
    public static void exportSealRecords(List<SealRecord> records, HttpServletResponse response) throws IOException {
        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();

        // 创建工作表
        Sheet sheet = workbook.createSheet("印章使用登记表");
        sheet.setDefaultColumnWidth(20);

        // 创建标题行样式
        CellStyle titleStyle = workbook.createCellStyle();
        Font titleFont = workbook.createFont();
        titleFont.setBold(true);
        titleFont.setFontHeightInPoints((short) 12);
        titleStyle.setFont(titleFont);
        titleStyle.setAlignment(HorizontalAlignment.CENTER);
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        titleStyle.setBorderTop(BorderStyle.THIN);
        titleStyle.setBorderBottom(BorderStyle.THIN);
        titleStyle.setBorderLeft(BorderStyle.THIN);
        titleStyle.setBorderRight(BorderStyle.THIN);

        // 创建内容行样式
        CellStyle contentStyle = workbook.createCellStyle();
        contentStyle.setAlignment(HorizontalAlignment.LEFT);
        contentStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        contentStyle.setBorderTop(BorderStyle.THIN);
        contentStyle.setBorderBottom(BorderStyle.THIN);
        contentStyle.setBorderLeft(BorderStyle.THIN);
        contentStyle.setBorderRight(BorderStyle.THIN);

        // 创建标题行
        Row titleRow = sheet.createRow(0);
        for (int i = 0; i < TITLES.length; i++) {
            Cell cell = titleRow.createCell(i);
            cell.setCellValue(TITLES[i]);
            cell.setCellStyle(titleStyle);
        }

        // 填充数据
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN);
        for (int i = 0; i < records.size(); i++) {
            SealRecord record = records.get(i);
            Row row = sheet.createRow(i + 1);

            // 序号
            Cell indexCell = row.createCell(0);
            indexCell.setCellValue(i + 1);
            indexCell.setCellStyle(contentStyle);

            // 使用日期
            Cell dateCell = row.createCell(1);
            Date recordDate = record.getDate();
            if (recordDate != null) {
                dateCell.setCellValue(sdf.format(recordDate));
            }
            dateCell.setCellStyle(contentStyle);

            // 使用原因
            Cell reasonCell = row.createCell(2);
            reasonCell.setCellValue(getSafeValue(record.getReason(), ""));
            reasonCell.setCellStyle(contentStyle);

            // 份数
            Cell copiesCell = row.createCell(3);
            copiesCell.setCellValue(getSafeValue(record.getCopies(), 0));
            copiesCell.setCellStyle(contentStyle);

            // 公章种类
            Cell typeCell = row.createCell(4);
            typeCell.setCellValue(getSealTypeName(record.getSealType()));
            typeCell.setCellStyle(contentStyle);

            // 经办人
            Cell handlerCell = row.createCell(5);
            handlerCell.setCellValue(getSafeValue(record.getHandler(), ""));
            handlerCell.setCellStyle(contentStyle);

            // 备注
            Cell remarkCell = row.createCell(6);
            remarkCell.setCellValue(getSafeValue(record.getRemarks(), ""));
            remarkCell.setCellStyle(contentStyle);
        }

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        String fileName = URLEncoder.encode("印章使用登记表_" + sdf.format(new Date()) + ".xlsx", "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName);

        // 写入响应流
        try (OutputStream os = response.getOutputStream()) {
            workbook.write(os);
            os.flush();
        } finally {
            workbook.close();
        }
    }
}